import requests
import time
import random
import string

class APIClient:
    def __init__(self, base_url, headers=None):
        self.base_url = base_url.rstrip("/")
        self.session = requests.Session()
        if headers:
            self.session.headers.update(headers)

    def _generate_dynamic_headers(self):
        """生成动态header"""
        return {
            "rt-request-id": ''.join(random.choices(string.ascii_letters + string.digits, k=10)),
            "rt-request-ts": str(int(time.time())),
        }

    def request(self, method, path, **kwargs):
        # 合并动态header和传入的header
        dynamic_headers = self._generate_dynamic_headers()
        if 'headers' in kwargs:
            kwargs['headers'] = {**dynamic_headers, **kwargs['headers']}
        else:
            kwargs['headers'] = dynamic_headers
        
        url = f"{self.base_url}{path}"
        try:
            response = self.session.request(method, url, **kwargs)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            print(f"[ERROR] {method.upper()} {url} 请求失败: {e}")
            return None

    # 其他方法保持不变...
    def get(self, path, **kwargs):
        return self.request("GET", path, **kwargs)

    def post(self, path, **kwargs):
        return self.request("POST", path, **kwargs)

    def put(self, path, **kwargs):
        return self.request("PUT", path, **kwargs)

    def delete(self, path, **kwargs):
        return self.request("DELETE", path, **kwargs)